package service

import (
	"CartApp/common"
	"CartApp/dao/mysql"
	"CartApp/models"
	"CartApp/pkg/e"
	"CartApp/pkg/util"
	"CartApp/serializer"

	"github.com/jinzhu/gorm"
	logging "github.com/sirupsen/logrus"
)

func Login(u *models.UserLogin) *serializer.Response {
	var user models.User
	code := e.SUCCESS
	if err := mysql.DB.Where("user_name=?", u.UserName).First(&user).Error; err != nil {
		//如果查询不到，返回相应的错误
		if gorm.IsRecordNotFoundError(err) {
			logging.Info(err)
			code = e.ErrorNotExistUser
			return &serializer.Response{
				Status: code,
				Msg:    e.GetMsg(code),
			}
		}
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}

	if common.CheckPassword(user.PasswordDigest, u.Password) == false {
		code = e.ErrorNotCompare
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}

	token, err := util.GenerateToken(user.ID, u.UserName, 0)
	if err != nil {
		logging.Info(err)
		code = e.ErrorAuthToken
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return &serializer.Response{
		Status: code,
		Data:   serializer.TokenData{User: serializer.BuildUser(user), Token: token},
		Msg:    e.GetMsg(code),
	}

}
